<template>
  <div class="ticket-management">
    <div class="ticket-header">
      <h3>票种管理</h3>
      <el-button type="primary" @click="openTicketDialog()" size="small" icon="Plus">添加票种</el-button>
    </div>

    <!-- 票种列表 -->
    <el-table
      v-loading="loading"
      :data="ticketList"
      style="width: 100%"
      border
    >
      <el-table-column
        prop="name"
        label="票种名称"
        min-width="100"
      />
      <el-table-column
        prop="price"
        label="价格"
        min-width="80"
      >
        <template #default="scope">
          <span>¥{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="totalStock"
        label="总库存"
        min-width="80"
      />
      <el-table-column
        prop="soldCount"
        label="已售数量"
        min-width="80"
      />
      <el-table-column
        prop="limitPerUser"
        label="每人限购"
        min-width="80"
      />
      <el-table-column
        prop="description"
        label="描述"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        min-width="150"
        fixed="right"
      >
        <template #default="scope">
          <el-button-group>
            <el-button size="small" type="primary" plain @click="openTicketDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="info" plain @click="viewTicketStats(scope.row)">数据</el-button>
            <el-button size="small" type="danger" plain @click="handleDeleteTicket(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 暂无数据时的提示 -->
    <el-empty v-if="!loading && ticketList.length === 0" description="暂无票种，点击上方按钮添加" />

    <!-- 票种表单对话框 -->
    <el-dialog
      v-model="ticketDialogVisible"
      :title="isEdit ? '编辑票种' : '添加票种'"
      width="500px"
      append-to-body
    >
      <el-form
        ref="ticketFormRef"
        :model="ticketForm"
        :rules="ticketRules"
        label-width="100px"
        status-icon
      >
      <el-form-item label="票种名称" prop="name">
  <el-select v-model="ticketForm.name" placeholder="请选择票种名称" style="width: 100%">
    <el-option label="成人票" value="成人票" />
    <el-option label="儿童票" value="儿童票" />
    <el-option label="学生票" value="学生票" />
    <el-option label="老年票" value="老年票" />
  </el-select>
</el-form-item>

        <el-form-item label="票价" prop="price">
          <el-input-number v-model="ticketForm.price" :precision="2" :step="10" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="总库存" prop="totalStock">
          <el-input-number v-model="ticketForm.totalStock" :min="1" :step="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="每人限购" prop="limitPerUser">
          <el-input-number v-model="ticketForm.limitPerUser" :min="1" :max="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="票种说明" prop="description">
          <el-input
            v-model="ticketForm.description"
            type="textarea"
            placeholder="输入票种说明"
            :rows="3"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ticketDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTicketForm" :loading="submitting">
            {{ isEdit ? '保存修改' : '添加票种' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 票种销售数据对话框 -->
    <el-dialog
      v-model="statsDialogVisible"
      title="票种销售数据"
      width="500px"
      append-to-body
    >
      <div class="stats-container" v-loading="statsLoading">
        <div v-if="ticketStats" class="stats-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="票种名称">{{ currentTicket.name }}</el-descriptions-item>
            <el-descriptions-item label="票价">¥{{ currentTicket.price }}</el-descriptions-item>
            <el-descriptions-item label="总库存">{{ currentTicket.totalStock }}</el-descriptions-item>
            <el-descriptions-item label="已售数量">{{ currentTicket.soldCount }}</el-descriptions-item>
            <el-descriptions-item label="剩余数量">{{ currentTicket.totalStock - currentTicket.soldCount }}</el-descriptions-item>
            <el-descriptions-item label="销售额">¥{{ (currentTicket.soldCount * currentTicket.price).toFixed(2) }}</el-descriptions-item>
            <el-descriptions-item label="销售比例">
              <el-progress 
                :percentage="Math.floor((currentTicket.soldCount / currentTicket.totalStock) * 100)" 
                :status="getProgressStatus(currentTicket.soldCount, currentTicket.totalStock)" 
              />
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-empty v-else description="暂无销售数据" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTicketList, createTicket, updateTicket, deleteTicket, getTicketStats } from '@/api/ticket'

const props = defineProps({
  eventId: {
    type: [Number, String],
    required: true
  },
  editable: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['update'])

// 票种列表和加载状态
const ticketList = ref([])
const loading = ref(false)
const submitting = ref(false)

// 票种表单对话框相关
const ticketDialogVisible = ref(false)
const ticketFormRef = ref(null)
const isEdit = ref(false)
const ticketForm = reactive({
  eventId: props.eventId,
  name: '',
  price: 0,
  totalStock: 100,
  limitPerUser: 1,
  description: ''
})

// 票种数据对话框相关
const statsDialogVisible = ref(false)
const statsLoading = ref(false)
const ticketStats = ref(null)
const currentTicket = ref({})

// 表单校验规则
const ticketRules = {
  name: [
    { required: true, message: '请输入票种名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入票价', trigger: 'blur' },
    { type: 'number', min: 0, message: '票价必须大于等于0', trigger: 'blur' }
  ],
  totalStock: [
    { required: true, message: '请输入总库存', trigger: 'blur' },
    { type: 'number', min: 1, message: '总库存必须大于0', trigger: 'blur' }
  ],
  limitPerUser: [
    { required: true, message: '请输入每人限购数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '限购数量必须大于0', trigger: 'blur' }
  ]
}

// 初始化获取票种列表
onMounted(() => {
  fetchTicketList()
})

// 获取票种列表
const fetchTicketList = async () => {
  loading.value = true
  try {
    const res = await getTicketList(props.eventId)
    if (res.code === 200) {
      ticketList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取票种列表失败')
    }
  } catch (error) {
    console.error('获取票种列表出错:', error)
    ElMessage.error('获取票种列表失败')
  } finally {
    loading.value = false
  }
}

// 打开票种表单对话框
const openTicketDialog = (row) => {
  if (!props.editable) {
    ElMessage.warning('当前状态不可编辑票种')
    return
  }
  
  resetTicketForm()
  
  if (row && row.id) {
    isEdit.value = true
    ticketForm.id = row.id
    Object.keys(ticketForm).forEach(key => {
      if (key in row) {
        ticketForm[key] = row[key]
      }
    })
  } else {
    isEdit.value = false
    ticketForm.eventId = props.eventId
  }
  
  ticketDialogVisible.value = true
}

// 重置票种表单
const resetTicketForm = () => {
  if (ticketFormRef.value) {
    ticketFormRef.value.resetFields()
  }
  
  Object.assign(ticketForm, {
    eventId: props.eventId,
    name: '',
    price: 0,
    totalStock: 100,
    limitPerUser: 1,
    description: ''
  })
}

// 提交票种表单
const submitTicketForm = async () => {
  if (!ticketFormRef.value) return
  
  await ticketFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        let res
        if (isEdit.value) {
          res = await updateTicket(props.eventId, ticketForm.id, ticketForm)
        } else {
          res = await createTicket(ticketForm)
        }
        
        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新票种成功' : '添加票种成功')
          ticketDialogVisible.value = false
          fetchTicketList()
          emit('update')
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '更新票种失败' : '添加票种失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '更新票种出错:' : '添加票种出错:', error)
        ElMessage.error(isEdit.value ? '更新票种失败' : '添加票种失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除票种
const handleDeleteTicket = (row) => {
  if (!props.editable) {
    ElMessage.warning('当前状态不可删除票种')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除票种"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await deleteTicket(row.id)
        if (res.code === 200) {
          ElMessage.success('删除票种成功')
          fetchTicketList()
          emit('update')
        } else {
          ElMessage.error(res.msg || '删除票种失败')
        }
      } catch (error) {
        console.error('删除票种出错:', error)
        ElMessage.error('删除票种失败')
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 查看票种销售数据
const viewTicketStats = async (row) => {
  statsDialogVisible.value = true
  currentTicket.value = row
  statsLoading.value = true
  
  try {
    const res = await getTicketStats(row.id)
    if (res.code === 200) {
      ticketStats.value = res.data || null
    } else {
      ElMessage.error(res.msg || '获取票种销售数据失败')
      ticketStats.value = null
    }
  } catch (error) {
    console.error('获取票种销售数据出错:', error)
    ElMessage.error('获取票种销售数据失败')
    ticketStats.value = null
  } finally {
    statsLoading.value = false
  }
}

// 根据销售比例获取进度条状态
const getProgressStatus = (sold, total) => {
  const percentage = sold / total
  if (percentage >= 0.8) return 'warning'
  if (percentage >= 1) return 'exception'
  return 'success'
}
</script>

<style scoped>
.ticket-management {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
}

.ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.ticket-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* 按钮样式修复 */
.ticket-header .el-button {
  color: #ffffff; /* 确保按钮文字为白色 */
}

.el-button-group .el-button {
  color: #5e5ce6; /* 普通按钮文字颜色 */
}

.el-button-group .el-button--danger {
  color: #ff375f; /* 危险按钮文字颜色 */
}

.el-button-group .el-button--info {
  color: #8e8e93; /* 信息按钮文字颜色 */
}

.el-button-group .el-button:hover {
  color: #ffffff; /* 悬停时文字颜色 */
}

.dialog-footer .el-button--primary {
  color: #ffffff; /* 对话框中确认按钮文字颜色 */
}

.stats-container {
  min-height: 200px;
}

.stats-info {
  padding: 10px;
}
</style> 